<template>
    <BasicModal v-bind="$attrs" @register="registerModal" showFooter :title="getTitle" width="35%" @ok="handleSubmit">
        <BasicForm @register="registerForm" />
    </BasicModal>
</template>
<script lang="ts" setup name="OrgModal">
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './index-option';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { saveOrgApi, updateOrgApi } from '/@/api/sys/org';
import { useMessage } from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();
const emit = defineEmits(['success']);
const getTitle = computed(() => (!unref(isUpdate) ? '新增组织机构' : '编辑组织机构'));
const isUpdate = ref(true);
const orgId = ref();

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
        orgId.value = data.orgId;
        setFieldsValue({
            ...data.record,
        });
    }
    setModalProps({ confirmLoading: false });
});

async function handleSubmit() {
    try {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        let res;
        if (unref(isUpdate)) {
            const param = { ...values, orgId: orgId.value };
            res = await updateOrgApi(param);
        } else {
            const param = { ...values, orgId: orgId.value };
            res = await saveOrgApi(param);
        }
        createMessage.success(res.msg);
        closeModal();
        emit('success');
    } finally {
        setModalProps({ confirmLoading: false });
    }
}
</script>
